package com.jzo2o.orders.manager.job;

import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.service.IOrdersCanceledService;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * 自动轮询取消订单
 * @author JIAN
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class OrderCancelJob {
    @Resource
    private IOrdersManagerService ordersManagerService;
    @Resource
    private IOrdersRefundService ordersRefundService;
    @Resource
    private IOrdersCanceledService ordersCanceledService;
    @Resource
    private TransactionTemplate transactionTemplate;

    @XxlJob("cancelPayOverTimeOrder")
    public void cancelPayOverTimeOrder() {
        List<Orders> orderList = ordersManagerService.getPayOverTimeOrder(100);
        if (CollUtils.isEmpty(orderList)) {
            log.info("没有超时订单");
            return;
        }

        // 取消所有超时未支付订单
        transactionTemplate.executeWithoutResult(status ->
                orderList.forEach(order -> ordersCanceledService.cancelPayOverTimeOrder(order)));
    }

    @XxlJob("handlerRefundOrder")
    public void handlerRefundOrder() {
        List<OrdersRefund> refundRecords = ordersRefundService.queryRefundOrderListByCount(100);
        if (CollUtils.isEmpty(refundRecords)) {
            log.info("没有正在退款的订单");
        }

        transactionTemplate.executeWithoutResult(status ->
                refundRecords.forEach(ordersRefundService::refundOrderByRefundRecord));
    }
}